import pyautogui
import time
import cv2
import numpy as np
from pynput import keyboard

# 全局控制开关
auto_fight_running = False

# 快捷键配置
KEY_BINDINGS = {
    'select': 'tab',
    'spell': '3',
    'physical': '2',
    'heal': '5',
    'pickup': '`'
}

# 基础操作函数
def press_key(key):
    pyautogui.press(key)

def select_target():
    press_key(KEY_BINDINGS['select'])

def cast_spell():
    press_key(KEY_BINDINGS['spell'])

def physical_attack():
    press_key(KEY_BINDINGS['physical'])

def heal():
    press_key(KEY_BINDINGS['heal'])

def pickup():
    press_key(KEY_BINDINGS['pickup'])

# 目标检测
def has_target(template):
    try:
        screenshot = pyautogui.screenshot()
        screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, _ = cv2.minMaxLoc(result)
        return max_val > 0.8  # 匹配阈值
    except:
        return False

# 主循环
def auto_fight_loop(template_path):
    global auto_fight_running
    
    # 加载模板
    template = cv2.imread(template_path)
    if template is None:
        print("无法加载血条模板")
        return

    attack_cycle = 0
    
    while auto_fight_running:
        # 选择目标
        select_target()
        time.sleep(0.5)  # 等待选中
        
        if has_target(template):
            # 攻击阶段
            if attack_cycle % 2 == 0:
                # 法术攻击阶段
                for _ in range(15):  # 15秒法术攻击
                    if not auto_fight_running: return
                    cast_spell()
                    time.sleep(1)
                
                # 治疗
                heal()
            else:
                # 物理攻击阶段
                for _ in range(10):  # 10秒物理攻击
                    if not auto_fight_running: return
                    physical_attack()
                    time.sleep(1)
                
                # 特殊技能
                press_key('4')
            
            attack_cycle += 1
        else:
            # 移动寻找目标
            for direction in ['up', 'right', 'down', 'left']:
                if not auto_fight_running: return
                pyautogui.keyDown(direction)
                time.sleep(2)
                pyautogui.keyUp(direction)
                select_target()
                if has_target(template):
                    break

# 键盘控制
def on_press(key):
    global auto_fight_running
    try:
        if key == keyboard.Key.f3:
            auto_fight_running = not auto_fight_running
            if auto_fight_running:
                print("自动打怪启动")
            else:
                print("自动打怪停止")
    except:
        pass

# 主函数
def main():
    # 启动监听
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    
    # 模板路径
    template_path = "health_bar_template.png"
    
    print("按F3开始/停止自动打怪")
    try:
        while True:
            if auto_fight_running:
                auto_fight_loop(template_path)
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("程序退出")

if __name__ == "__main__":
    main()